package top.sdaily.schedule;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Created by admin on 2017/3/17.
 */
public class CircleQueueSchedule {

    private final CircleQueue<List<ScheduleTask>> circleQueue;
    private final ExecutorService threadPool = Executors.newCachedThreadPool();
    private List<ScheduleTask> waitPool;
    private static int capacity = 3600;
    private LocalDate schedulerStartTime;

    public CircleQueueSchedule () {
        circleQueue = new CircleQueue<List<ScheduleTask>>(capacity);
        waitPool = new ArrayList<ScheduleTask>();
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(new CircleQueueScheduleRunnable());
        schedulerStartTime = LocalDate.now();
    }

    public CircleQueue<List<ScheduleTask>> getCircleQueue() {
        return circleQueue;
    }

    public List<ScheduleTask> getWaitPool() {
        return waitPool;
    }

    /**
     * 装载定时任务
     * @param scheduleTask
     */
    public void loadScheduleTask(ScheduleTask scheduleTask){
        // ======================================================
        // TODO: 2017/3/28 根据scheduleTask对象计算放置的位置
        // 执行时间不处在当前执行队列则放入等待池
        // ======================================================
    }

    /**
     * 载入满足当前队列长度的定时任务
     */
    private void loadScheduleTaskInWaitPool () {

    }

    class CircleQueueScheduleRunnable implements Runnable {
        @Override
        public void run() {
            List<ScheduleTask> scheduleTaskList = circleQueue.getCurrentData();
            int currentPosition = circleQueue.getCurrentPosition();
            System.out.println(currentPosition);
            circleQueue.moveNext();
            if (scheduleTaskList != null) {
                for (ScheduleTask scheduleTask : scheduleTaskList) {
                    Future<?> submit = threadPool.submit(scheduleTask);
                    try {
                        submit.get();
                    } catch (Exception e){
                        System.out.println("执行定时任务出错：" + scheduleTask.getName() + " -- "+ e.getMessage());
                    }
                }
            }

            if (currentPosition + 1 == capacity) {
                loadScheduleTaskInWaitPool();
            }
        }
    }
}
